<script setup>
import {ref, onMounted, computed} from 'vue';
import {ElMessage} from 'element-plus';
import {confirmPickup, handleException} from '../services/api';
import {useStore} from 'vuex';

const loading = ref(false);
const filterStatus = ref('all');
const store = useStore();
const orders = computed(() => store.state.orders);
import {onBeforeUnmount} from 'vue';
import {CircleCheck, Close, Plus, Refresh, Warning} from "@element-plus/icons-vue";

let socket = null;

const initWebSocket = () => {
  socket = new WebSocket('ws://your-backend/ws/orders');

  socket.onmessage = (event) => {
    const updatedOrder = JSON.parse(event.data);
    store.commit('UPDATE_ORDER_STATUS', {
      orderId: updatedOrder.id,
      status: updatedOrder.status
    });
  };
};

onMounted(() => {
  initWebSocket();
});

onBeforeUnmount(() => {
  socket?.close();
});
// 获取订单列表
const fetchOrders = () => {
  loading.value = true;
  store.dispatch('fetchOrders', filterStatus.value)
      .catch(error => {
        console.error("获取订单失败", error);
        ElMessage.error({message: '获取订单失败', duration: 1000});
      })
      .finally(() => loading.value = false);  // 调整执行顺序
};
// 组件挂载时获取订单
onMounted(() => {
  fetchOrders();
});

// 确认取件处理
const handleConfirmPickup = (orderId) => {
  confirmPickup(orderId).then(() => {
    ElMessage.success("取件确认成功");
    fetchOrders(); // 刷新订单列表
  }).catch(error => {
    console.error("取件确认失败", error);
    ElMessage.error({message: '取件确认失败', duration: 1000});
  });
};

// 处理异常订单
const handleOrderException = (orderId) => {
  handleException(orderId).then(() => {
    ElMessage.success("异常处理成功");
    fetchOrders(); // 刷新订单列表
  }).catch(error => {
    console.error("异常处理失败", error);
    ElMessage.error({message: '异常处理失败', duration: 1000});
  });
};

// 取消订单处理
const handleCancelOrder = (orderId) => {
  store.dispatch('cancelOrder', orderId).then(() => {
    ElMessage.success({message: '订单取消成功', duration: 1000});
    fetchOrders(); // 刷新订单列表
  }).catch(error => {
    console.error("订单取消失败", error);
    ElMessage.error({message: '订单取消失败', duration: 1000});
  });
};
// 状态显示映射
const statusType = (status) => {
  const types = {
    'CREATED': 'primary',
    'SHIPPED': 'warning',
    'COMPLETED': 'success',
    'ABNORMAL': 'danger'
  };
  return types[status] || 'info';
};

const statusText = (status) => {
  const texts = {
    'CREATED': '已下单',
    'SHIPPED': '运输中',
    'COMPLETED': '已完成',
    'ABNORMAL': '异常'
  };
  return texts[status] || '未知状态';
};

</script>

<template>
  <div class="order-container">
    <div class="filter-section">
      <label for="statusFilter">筛选状态:</label>
      <el-select
          v-model="filterStatus"
          @change="handleFilterChange"
          placeholder="请选择状态"
          :disabled="loading"
          style="width: 200px"
      >
        <el-option value="all">全部</el-option>
        <el-option value="ordered">已下单</el-option>
        <el-option value="shipped">已寄送</el-option>
        <el-option value="picked_up">已取件</el-option>
        <el-option value="exception">异常</el-option>
      </el-select>
    </div>

    <div class="orders-list">
      <!-- 加载状态 -->
      <template v-if="loading">
        <el-skeleton
            v-for="i in 3"
            :key="`skeleton-${i}`"
            :rows="5"
            animated
            class="skeleton-item"
        />
      </template>

      <!-- 数据加载完成状态 -->
      <template v-else>
        <!-- 有订单数据时 -->
        <template v-if="orders && orders.length > 0">
          <div
              v-for="order in orders"
              :key="order.id"
              class="order-card"
          >
            <h2 class="order-id">订单号: {{ order.id || '--' }}</h2>
            <div class="order-detail">
              <p v-if="order.sender"><strong>寄件人:</strong> {{ order.sender }}</p>
              <p v-if="order.receiver"><strong>收件人:</strong> {{ order.receiver }}</p>
              <p><strong>快递柜信息:</strong> {{ order.lockerInfo || '暂无信息' }}</p>
              <div class="status-section">
                <strong>订单状态:</strong>
                <el-tag
                    :type="getStatusType(order.status)"
                    effect="light"
                    class="status-tag"
                >
                  {{ getStatusText(order.status) }}
                </el-tag>
              </div>
            </div>

            <div class="action-buttons">
              <!-- 运输中状态操作 -->
              <el-button
                  v-if="order.status === 'SHIPPED'"
                  type="primary"
                  size="small"
                  @click="handleConfirmPickup(order.id)"
                  :loading="pickupLoading[order.id]"
              >
                <el-icon class="button-icon"><CircleCheck /></el-icon>
                确认取件
              </el-button>

              <!-- 异常状态操作 -->
              <el-button
                  v-if="order.status === 'ABNORMAL'"
                  type="danger"
                  size="small"
                  @click="handleOrderException(order.id)"
              >
                <el-icon class="button-icon"><Warning /></el-icon>
                处理异常
              </el-button>

              <!-- 可取消订单状态 -->
              <el-button
                  v-if="isCancelable(order.status)"
                  type="danger"
                  size="small"
                  plain
                  @click="handleCancelOrder(order.id)"
              >
                <el-icon class="button-icon"><Close /></el-icon>
                取消订单
              </el-button>
            </div>
          </div>
        </template>

        <!-- 无数据空状态 -->
        <el-empty
            v-else
            :image="emptyImage"
            :image-size="180"
            description="没有找到相关订单"
        >
          <div class="empty-actions">
            <el-button
                type="primary"
                @click="fetchOrders"
                :loading="loading"
            >
              <el-icon><Refresh /></el-icon>
              刷新试试
            </el-button>
            <el-button plain @click="$router.push('/new-order')">
              <el-icon><Plus /></el-icon>
              创建新订单
            </el-button>
          </div>
        </el-empty>
      </template>
    </div>
  </div>
</template>
<style scoped>
.order-container {
  width: 1200px;
  margin: 0 auto;
  height: 100%;
  padding: 24px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease-in-out;
}

.filter-section {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.filter-section label {
  margin-right: 12px;
  font-size: 16px;
  color: #303133;
}

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.order-card {
  background-color: #f9fafb;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.order-card h2 {
  font-size: 20px;
  color: #303133;
  margin-bottom: 12px;
}

.order-card p {
  font-size: 16px;
  color: #606266;
  margin-bottom: 8px;
}

.button-group {
  display: flex;
  gap: 12px;
  margin-top: 12px;
}

.el-button {
  height: 36px;
  padding: 0 16px;
  font-size: 14px;
}

@media (max-width: 768px) {
  .order-container {
    padding: 16px;
  }

  .filter-section label {
    font-size: 14px;
  }

  .order-card h2 {
    font-size: 18px;
  }

  .order-card p {
    font-size: 14px;
  }
}
</style>



